export default defineEventHandler(async (event) => {
  const body = await readBody(event)
  const { code, redirect_uri } = body

  if (!code) {
    throw createError({
      statusCode: 400,
      statusMessage: 'Authorization code is required'
    })
  }

  try {
    // Google OAuth 配置
    const GOOGLE_CLIENT_ID = process.env.GOOGLE_CLIENT_ID || '420168086989-flb4p9l7cbt1i9iqldqq08o2fqec4bmf.apps.googleusercontent.com'
    const GOOGLE_CLIENT_SECRET = process.env.GOOGLE_CLIENT_SECRET || 'YOUR_GOOGLE_CLIENT_SECRET'
    const GOOGLE_TOKEN_URL = 'https://oauth2.googleapis.com/token'
    const GOOGLE_USER_INFO_URL = 'https://www.googleapis.com/oauth2/v2/userinfo'

    // 1. 使用授权码交换访问令牌
    const tokenResponse = await $fetch(GOOGLE_TOKEN_URL, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
      },
      body: new URLSearchParams({
        client_id: GOOGLE_CLIENT_ID,
        client_secret: GOOGLE_CLIENT_SECRET,
        code: code,
        grant_type: 'authorization_code',
        redirect_uri: redirect_uri
      })
    })

    const { access_token } = tokenResponse

    // 2. 使用访问令牌获取用户信息
    const userInfoResponse = await $fetch(GOOGLE_USER_INFO_URL, {
      headers: {
        'Authorization': `Bearer ${access_token}`
      }
    })

    // 3. 处理用户信息
    const user = {
      id: userInfoResponse.id,
      email: userInfoResponse.email,
      name: userInfoResponse.name,
      picture: userInfoResponse.picture,
      provider: 'google'
    }

    // 4. 生成JWT令牌（这里简化处理，实际项目中应该使用更安全的方式）
    const token = Buffer.from(JSON.stringify(user)).toString('base64')

    // 5. 返回成功响应
    return {
      success: true,
      user,
      token,
      message: 'Google login successful'
    }

  } catch (error) {
    console.error('Google OAuth error:', error)
    
    throw createError({
      statusCode: 500,
      statusMessage: 'Failed to authenticate with Google'
    })
  }
}) 